//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "var.h"
#include "SetPort.h"


//---------------------------------------------------------------------------

#pragma package(smart_init)
char InBuffer[SERIAL232NUM][300];
char OutBuffer[SERIAL232NUM][300];

extern HANDLE hCOM[SERIAL232NUM];

DWORD       nBytesRead;
DWORD       nBytesWrite;

//--------포트 오픈------------------------------------------------------
HANDLE OpenComPort(int num)
{
    HANDLE hCom;

    switch(num)
    {
        case 0:
                hCom = CreateFile("COM1", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 1:
                hCom = CreateFile("COM2", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 2:
                hCom = CreateFile("COM3", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 3:
                hCom = CreateFile("COM4", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 4:
                hCom = CreateFile("COM5", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 5:
                hCom = CreateFile("COM6", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 6:
                hCom = CreateFile("COM7", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        case 7:
                hCom = CreateFile("COM8", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;
        default:
                hCom = CreateFile("COM9", GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                break;

    }

    return hCom;

}

//--------포트 초기화 -----------------------------------------------------
HANDLE serial_init_com(int num)
{
    DCB                 dcb;
    COMMTIMEOUTS        TimeOut;
    COMMPROP            ipCommProp;
    HANDLE              ComHandle;

    memset(&dcb,0,sizeof(dcb));
    memset(&TimeOut,0,sizeof(TimeOut));

    ComHandle = OpenComPort(num);      // COM port Open.
    if (ComHandle == INVALID_HANDLE_VALUE) return 0; //COM Open Error

    SetupComm(ComHandle,300,300);      // 통신포트 버퍼 설정

    dcb.fBinary  = true;               // 이진모드 지정 true
    dcb.BaudRate = CBR_9600;          // 통신포트의 전송속도 지정한다 (19200bps)
    dcb.ByteSize = 8;                  //
    dcb.StopBits = ONESTOPBIT;         // ONESTOPBIT = 1개의 스톱비트를 가진다.
    dcb.Parity   = NOPARITY;           // 패리티 검사여부 지정한다.

    // 새로운 상태를 지정한다.
    if (!SetCommState(ComHandle, &dcb))
    {
        CloseHandle(ComHandle);
        return 0;
    }

    //통신포트의 현재 DCB를 돌려준다.
    if (GetCommState(ComHandle, &dcb))
    {
    }

    GetCommProperties(ComHandle,&ipCommProp);

    if(ipCommProp.dwProvCapabilities & PCF_INTTIMEOUTS)
    {
         TimeOut.ReadIntervalTimeout = MAXDWORD;
         SetCommTimeouts(ComHandle,&TimeOut);            // 타임아웃 사용안함 설정
    }
    else ;
    return ComHandle;
}
//----------------------------------------------------------------------------
void CommError(DWORD dwError,HANDLE hc)      // 송수신 에러시.
{
    register LONG       lrc;
    register COMSTAT    cs;

    // Error Processing
    ClearCommError(hc,(LPDWORD)&lrc,&cs);
    CloseHandle(hc);
}

// 포트 닫기
void serial_close_com(HANDLE hc)
{
    if(hc)
    {
        PurgeComm(hc,PURGE_RXCLEAR|PURGE_TXCLEAR);
        CloseHandle(hc);
    }
}

BOOL    WriteData(int num, char* message)
{
        AnsiString str = message;
        AnsiString sTemp;
        memset(OutBuffer[num],NULL,sizeof(OutBuffer[num]));

        char ch = 0x05;
        sTemp = ch;
        str = sTemp + str;

        ch = 0x0D;
        sTemp = ch;
        str = str + sTemp;

        strcpy(OutBuffer[num],str.c_str());

        if(!WriteFile(hCOM[num],OutBuffer[num],sizeof(OutBuffer),&nBytesWrite,NULL))
        {

                return false;
        }
        else
        {
                return true;
        }


}

// 수신
BOOL    ReadData(int num, char* message)
{
        memset(InBuffer[num],NULL,sizeof(InBuffer[num]));
        strcpy(InBuffer[num],message);

        if(!ReadFile(hCOM[num],InBuffer[num],sizeof(InBuffer),&nBytesRead,NULL))
        {

                return false;
        }
        else
        {
                return true;
        }
}



//--------------------------------------------------------------------------
//  Serial Messages.
//--------------------------------------------------------------------------

